<!doctype html>
<html>
<head>
	<meta charset="utf-8"/>
	<title>抓鬼</title>
	
</head>
<body>
<script>
var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");
  canvas.width = 512;
  canvas.height= 480;
  document.body.appendChild(canvas);

  var bgReady = false;
  var heroReady = false;
  var monsterReady = false;
  var bgImage = new Image();
  var heroImage = new Image();
  var monsterImage = new Image();
  bgImage.onload = function() {
    bgReady = true;   //背景图片加载成功时的判断。
    heroReady = true;
    monsterReady = true;
  } 
  bgImage.src= "http://sandbox.runjs.cn/uploads/rs/244/f1gv147l/background.png";//设置好后将在加载时应用
    heroImage.src="http://sandbox.runjs.cn/uploads/rs/244/f1gv147l/hero.png";
    monsterImage.src = "http://sandbox.runjs.cn/uploads/rs/244/f1gv147l/monster.png";

  //设置人物参数
  var hero = {
    speed:256,
    x:0,
    y:0
  }
  var monster ={
    x:0,
    y:0
  }
  var caught = 0;

//设置键盘事件
var keysDown = {};  
addEventListener("keydown", function (e) {  
     keysDown[e.keyCode] = true;  
}, false);  
addEventListener("keyup", function (e) {  
     delete keysDown[e.keyCode];  
}, false);  


//初始化游戏
  function reset() {
    hero.x = canvas.width/2;
    hero.y = canvas.height/2;
   
   monster.x = 32 + Math.random()*(canvas.width-64);
   monster.y = 32 + Math.random()*(canvas.height-64);
  }
//初始化游戏
  function start() {
    
   
   monster.x = 32 + Math.random()*(canvas.width-64);
   monster.y = 32 + Math.random()*(canvas.height-64);
  }
 //更新动作
  function  update(modifier) {
    var changePosition = hero.speed*modifier;
    if(38 in keysDown) {   //上键
      if(hero.y >32)hero.y -= changePosition;
    }
    if(40 in keysDown) {
      if(hero.y <canvas.height-64)hero.y += changePosition;
    }
    if(37 in keysDown) {
      if(hero.x >32)hero.x -= changePosition;
    }
    if(39 in keysDown) {
      if(hero.x<canvas.width-64)hero.x += changePosition;
    }
   if (  
        hero.x <= (monster.x + 32)  
            && monster.x <= (hero.x + 32)  
            && hero.y <= (monster.y + 32)  
            && monster.y <= (hero.y + 32)  
    ) {  
         caught++;  
         start();  
    }   
  }
  var render = function () {  
    if (bgReady) {  
         ctx.drawImage(bgImage, 0, 0);  
    }  
  
    if (heroReady) {  
         ctx.drawImage(heroImage, hero.x, hero.y);  
    }  
  
    if (monsterReady) {  
         ctx.drawImage(monsterImage, monster.x, monster.y);  
    }  
  
  
    ctx.fillStyle = "rgb(250, 250, 250)";  
    ctx.font = "24px Helvetica";  
    ctx.textAlign = "left";  
    ctx.textBaseline = "top";  
    ctx.fillText("抓鬼次数: " + caught, 32, 32);  
};  

var main = function () {  
    var now = Date.now();  
    var delta = now - then;  
  
    update(delta / 1000);  
    render();  
  
    then = now;  
};  
reset();  
var then = Date.now();  
setInterval(main, 1); </script>
</body>
</html>   	
